<template>
  <div class="mod-category main-container">
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('prod:category:save')"
          class="default-btn primary-btn"
          @click="onAddOrUpdate()"
        >
          {{ $t("crud.addTitle") }}
        </div>
        <div
          v-if="isAuth('prod:category:export')"
          class="default-btn primary-btn"
          @click="exportCategory()"
        >
          {{ $t("order.ExportingFiles") }}
        </div>
      </div>
      <div class="table-con">
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          row-key="categoryId"
          style="width: 100%;"
        >
          <el-table-column
            prop="categoryName"
            tree-key="categoryId"
            align="left"
            :label="$t('publics.categoryCn')"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.categoryName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            align="left"
            :label="$t('product.status')"
          >
            <template #default="scope">
              <span
                v-if="scope.row.status === 0"
                class="tag-text"
              >{{ $t("live.offline") }}</span>
              <span
                v-else
                class="tag-text"
              >{{ $t("publics.normal") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="seq"
            align="left"
            width="150"
            :label="$t('hotSearch.seq')"
          />
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('text.menu')"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('prod:category:update')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.categoryId)"
                >
                  {{ $t("groups.edit") }}
                </div>
                <div
                  v-if="isAuth('prod:category:delete')"
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.categoryId)"
                >
                  {{ $t("text.delBtn") }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-pagination
      layout="total,sizes, prev, pager, next, jumper"
      :current-page="pages.current"
      :page-size="pages.size"
      :total="pages.total"
      :page-sizes="[10, 20, 30, 40]"
      @size-change="onPageSizeChange"
      @current-change="onPageNumChange"
    />

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="getDataList(pages.current)"
    />
  </div>
</template>

<script setup>
import { isAuth } from '@/utils/index.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import AddOrUpdate from './add-or-update.vue'

const pages = reactive({
  total: 0, // 总页数
  current: 1, // 当前页数
  size: 10 // 每页显示多少条
})

onMounted(() => {
  getDataList()
})

/**
 * 分页页面变化时刷新数据
 * @param page
 */
const onPageNumChange = (page) => {
  getDataList(page)
}
/**
 * 分页页目大小变化时刷新数据
 * @param size
 */
const onPageSizeChange = (size) => {
  pages.size = size
  getDataList()
}
// 获取数据列表
const dataList = ref([])
const getDataList = (current = 1) => {
  http({
    url: http.adornUrl('/prod/category/pageCategory'),
    method: 'get',
    params: http.adornParams({
      current,
      size: pages.size
    })
  }).then(({ data }) => {
    pages.total = data.total
    pages.current = data.current
    dataList.value = data.records
  })
}
// 新增 / 修改
const addOrUpdateRef = ref(null)
const addOrUpdateVisible = ref(false)
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}
// 删除
const onDelete = (id) => {
  ElMessageBox.confirm(`${$t('sys.makeSure')}[${$t('text.delBtn')}]${$t('text.menu')}?`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl(`/prod/category/${id}`),
      method: 'delete',
      data: http.adornData()
    }).then(() => {
      if (dataList.value.length === 1 && pages.current > 1) {
        pages.current--
      }
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          getDataList(pages.current)
        }
      })
    })
  })
}

// 导出
const exportCategory = () => {
  const loading = ElLoading.service({
    lock: true,
    target: '.mod-category',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('formData.exportIng')
  })
  http({
    url: http.adornUrl('/prod/category/export'),
    method: 'get',
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('category.exportXls')
    const elink = document.createElement('a')
    if ('download' in elink) {
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
    } else {
      navigator.msSaveBlob(blob, fileName)
    }
    ElMessage({
      message: $t('stock.exportSuccess'),
      type: 'success',
      duration: 1500
    })
  }).catch(() => {
    loading.close()
  })
}

</script>

<style lang="scss" scoped>
.main-container {
  margin-top: 0;
  padding-top: 0;
}
</style>
